//
//  RBDataBaseManager.m
//  FD
//
//  Created by xiaofang wang on 2018/11/22.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  本地数据库
/**
 sql 数据类型
 blod NSData,可用于image、归档后的对象
 */
//数据库名字 fudi.sqlite
//表名 msgTable

#import "RBDataBaseManager.h"
#import "FMDB.h"

@interface RBDataBaseManager()
//databaseQueue对象 线程安全的
@property (nonatomic, strong) FMDatabaseQueue *dbQueue;

@end

@implementation RBDataBaseManager
#pragma mark - 一 初始化数据库
//单例对象
+ (instancetype)shareDataBaseQueueManager {
    static RBDataBaseManager *manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[RBDataBaseManager alloc] init];
    });
    
    return manger;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //1.获取沙盒路径
        NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        
        //2.创建数据库文件路径
        NSString *path = [dir stringByAppendingPathComponent:@"fudi.sqlite"]; //数据库名字
        FDLog(@"本地数据库路径:%@",path);
        
        //3.根据路径创建一个FMDataBaseQueue对象
        self.dbQueue = [[FMDatabaseQueue alloc] initWithPath:path];
        //4.创建一张表
        [self createMessageTable];
    }
    return self;
}


- (void)createMessageTable {
    
    NSString *sqlStr = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS msgTable(messageId TEXT PRIMARY KEY NOT NULL, type , title, thumbnail,  resource,  createTime ,isRead)"];
    
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        if ([db executeUpdate:sqlStr]) {
            FDLog(@"创建表成功");
        }else {
            FDLog(@"创建表失败");
        }
    }];
}



#pragma mark - 二 接口

/**1.插入一个数据**/
- (void)addMessageModel:(PushMsgModel *)model {
    //OC只能存对象,直接奔溃
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO msgTable(messageId, type, title, thumbnail, resource, createTime, isRead) values(?,?,?,?,?,?,?)"];
    
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        BOOL isSuccess = [db executeUpdate:sql,model.messageId,model.type,model.title,model.thumbnail,model.resource,model.createTime,@(model.isRead)]; //Bool包装成对象
        FDLog(@"%@",isSuccess ? @"插入成功" : @"插入失败");
    }];
}



/**2.查询所有的数据*/
- (NSArray *)selectAllMessage {
    //容器
    NSMutableArray *vesselArrM = @[].mutableCopy;
    
    //2.sql语句
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM msgTable"];
    //3.执行sql
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        FMResultSet *res = [db executeQuery:sqlStr];
        while ([res next]) {
            
            //3-1查询结果
            NSString *msgId = [res stringForColumn:@"messageId"];
            NSString *type = [res stringForColumn:@"type"];
            NSString *title = [res stringForColumn:@"title"];
            NSString *thumbnail = [res stringForColumn:@"thumbnail"];
            NSString *resource = [res stringForColumn:@"resource"];
            NSNumber *createTime = @([[res stringForColumn:@"createTime"] doubleValue]); //@([[res stringForColumn:@"createTime"] floatValue]);
            BOOL isRead = [[res stringForColumn:@"isRead"] doubleValue];
            
            //3-2包装成对象
            PushMsgModel *model = [[PushMsgModel alloc] init];
            model.messageId = msgId;
            model.type = type;
            model.title = title;
            model.thumbnail = thumbnail;
            model.resource = resource;
            model.createTime= createTime;
            model.isRead = isRead;
            
            //非空才添加
            if (model != nil) {
                //3-3存入数组中
                [vesselArrM addObject:model];
            }
        }
    }];
    
    
    
    //2019-2-19 时间倒序
    NSArray *sortedArr = [vesselArrM sortedArrayUsingComparator:^NSComparisonResult(PushMsgModel *obj1, PushMsgModel * obj2) {
        if ([obj1.createTime doubleValue] < [obj2.createTime doubleValue]) {
            return NSOrderedDescending;
        }else if ([obj1.createTime doubleValue] == [obj2.createTime doubleValue]) {
            return NSOrderedSame;
        }else {
            return NSOrderedAscending;
        }
    }];
    

    //4.返回
    //    return [vesselArrM copy];
    return sortedArr;
}


/**3.删除一条消息*/
- (void)deleteMessageModelMsgId:(NSString *)msgId {
    //1.sql语句, 根据msgId 删除
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM msgTable WHERE messageId = '%@'",msgId];
    
    //2.执行sql语句
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        BOOL isDeleteSuccess = [db executeUpdate:sqlStr];
        FDLog(@"%@",isDeleteSuccess ? @"删除成功" : @"删除失败");
    }];
}

/**5.更新读写状态  已读 未读*/
- (void)updateReadStateWithMsgId:(NSString *)msgId {
    //坑⚠️ 请给messageid 加上 ''
    NSString *sql = [NSString stringWithFormat:@"UPDATE msgTable SET isRead = 1 where messageId = '%@'",msgId];
    //UPDATE msgTable SET isRead = 1 where messageId = '00ebf421-4e62-4900-9122-cfb2d04f2568'
    //'00ebf421-4e62-4900-9122-cfb2d04f2568' 应为中间有-必须加上引号表示他们是一个整体。
    
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        BOOL isUpdateSuccess = [db executeUpdate:sql];
        FDLog(@"%@",isUpdateSuccess ? @"更新成功" : @"更新失败");
    }];
}

/**6.批量更新读写状态 一键已读*/
- (void)updateReadAll:(BOOL)isAll {
    
    NSString *sql = [NSString stringWithFormat:@"UPDATE msgTable SET isRead = %@",@(isAll)];
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        BOOL isReadAll = [db executeUpdate:sql];
        FDLog(@"%@",isReadAll ? @"成功'一键已读'" : @"失败'一键已读'");
    }];
}


@end
